package com.adobe.apprise.commands
{
	import com.adobe.air.alert.NativeAlert;
	import com.adobe.apprise.events.AddFeedEvent;
	import com.adobe.apprise.events.AggregateEvent;
	import com.adobe.apprise.events.BusyEvent;
	import com.adobe.apprise.model.ModelLocator;
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	
	import flash.desktop.NativeApplication;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.TimerEvent;
	import flash.html.HTMLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLStream;
	import flash.utils.Timer;
	
	import mx.resources.ResourceManager;
	
	public class AddFeedCommand implements ICommand
	{
		public function execute(ce:CairngormEvent):void
		{
			var addFeedEvent:AddFeedEvent = ce as AddFeedEvent;		
			var feedUrl:String = addFeedEvent.feedUrl;			
			var stream:URLStream = new URLStream();

			stream.addEventListener(IOErrorEvent.IO_ERROR,
				function(e:IOErrorEvent):void
				{
					var errorMessage:String = ResourceManager.getInstance().getString('resources','ADDFEED_IO_ERROR').replace("$1",feedUrl);
					var errorTitle:String = ResourceManager.getInstance().getString('resources','ADDFEED_ERROR_TITLE');
					NativeAlert.show(errorMessage,errorTitle,NativeAlert.OK,true,NativeApplication.nativeApplication.activeWindow);
				});			
			
			stream.addEventListener(HTTPStatusEvent.HTTP_RESPONSE_STATUS,
				function(e:HTTPStatusEvent):void
				{
					for each ( var tag:URLRequestHeader in e.responseHeaders )
					{
						if ( new RegExp("content.type","i").exec(tag.name) )
						{
							if ( new RegExp("text\/html","i").exec(tag.value) ) 
							{
								extractAlternateURL(feedUrl);
								break;
							}
							else if ( new RegExp("(application|text)\/(rss|xml|atom|rdf)","i").exec(tag.value) )
							{
								var aggregateEvent:AggregateEvent = new AggregateEvent();
								aggregateEvent.feeds = [feedUrl]; //dispatch with original URL
								aggregateEvent.dispatch();
								break;
							}					
						}
					}
				});

			stream.load(new URLRequest(feedUrl));
		}
		
		private function extractAlternateURL(feedUrl:String):void
		{
			var htmlLoader:HTMLLoader = new HTMLLoader();
			
			htmlLoader.addEventListener(Event.COMPLETE,
				function(e:Event):void
				{	
					timeout.stop();
					//get the <link> tags from the HTMLLoader, which has encapsulated the data
					var linkArray:Object = htmlLoader.window.document.getElementsByTagName("link");
					var o:Object;
					for ( var i:uint = 0; i < linkArray.length; i++)
					{
						o = linkArray[i];
						if ( o["rel"].toLowerCase() == "alternate" )
						{
							if ( new RegExp("(xml|rss|atom|rdf)","i").test(o["type"]) )
							{			
								var be:BusyEvent = new BusyEvent();
								be.busy = false;
								be.dispatch();
								var aggregateEvent:AggregateEvent = new AggregateEvent();
								aggregateEvent.feeds = [o["href"]]; //dispatch with updated URL
								aggregateEvent.dispatch();		
								return;
							}
						}
					}
					var busyEvent:BusyEvent = new BusyEvent();
					busyEvent.busy = false;
					busyEvent.dispatch();
					
					var errorMessage:String = ResourceManager.getInstance().getString("resources","ADDFEED_FEED_NO_ALTERNATE").replace("$1",feedUrl);
					var errorTitle:String = ResourceManager.getInstance().getString("resources","ADDFEED_ERROR_TITLE");
					NativeAlert.show(errorMessage,errorTitle,NativeAlert.OK,true,NativeApplication.nativeApplication.activeWindow);

					//change status bar to "Done."
					ModelLocator.getInstance().statusMessage = ResourceManager.getInstance().getString("resources","POSTDISPLAY_STATUS_DONE");
				});

			htmlLoader.load(new URLRequest(feedUrl));
			
			var timeout:Timer = new Timer(30000); 
			timeout.addEventListener(TimerEvent.TIMER,
				function(e:TimerEvent):void
				{
					var busyEvent:BusyEvent = new BusyEvent();
					busyEvent.busy = false;
					busyEvent.dispatch();
					htmlLoader.cancelLoad();
					timeout.stop();
					
					//display error ("couldn't resolve url")
					var errorMessage:String = ResourceManager.getInstance().getString("resources","ADDFEED_FEED_SEARCH_FAIL").replace("$1",feedUrl);
					var errorTitle:String = ResourceManager.getInstance().getString("resources","ADDFEED_ERROR_TITLE");
					NativeAlert.show(errorMessage,errorTitle,NativeAlert.OK,true,NativeApplication.nativeApplication.activeWindow);
					
					//change status bar to "Done."
					ModelLocator.getInstance().statusMessage = ResourceManager.getInstance().getString("resources","POSTDISPLAY_STATUS_DONE");
				});
				
			timeout.start();
			
			var busyEvent:BusyEvent = new BusyEvent();
			busyEvent.busy = true;
			busyEvent.dispatch();
			ModelLocator.getInstance().statusMessage = ResourceManager.getInstance().getString("resources","ADDFEED_FEED_SEARCH").replace("$1",feedUrl);
		}
	}
}
